<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="订单编号" prop="opId">
        <el-input v-model="queryParams.opId" placeholder="请输入订单编号" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="产品编号" prop="ppId">
        <el-input v-model="queryParams.ppId" placeholder="请输入产品编号" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="生产数量" prop="proQty">
        <el-input v-model="queryParams.proQty" placeholder="请输入生产数量" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="订单状态" prop="opState">
        <el-input v-model="queryParams.opState" placeholder="请输入订单状态" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <!--      <el-form-item label="计划开始日期" prop="planStartTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.planStartTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择计划开始日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="计划结束日期" prop="planEndTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.planEndTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择计划结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="开始日期" prop="startTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.startTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择开始日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="结束日期" prop="endTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.endTime"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择结束日期">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="帐号状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择帐号状态" clearable size="small">
          <el-option label="请选择字典生成" value="" />
        </el-select>
      </el-form-item> -->
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['mes:order_product:add']">新增</el-button>
      </el-col>
      <!--      <el-col :span="1.5">
        <el-button type="success" icon="el-icon-edit" size="mini" :disabled="single" @click="handleUpdate" v-hasPermi="['mes:order_product:edit']">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete"
          v-hasPermi="['mes:order_product:remove']">删除</el-button>
      </el-col> -->
      <el-col :span="1.5">
        <!--        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['mes:order_product:export']"
        >导出</el-button> -->
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="order_productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="ID" align="center" prop="id" v-if="false" />
      <el-table-column label="订单编号" align="center" prop="opId" width="160">


      </el-table-column>

      <el-table-column label="产品" align="center">
        <template slot-scope="scope">
          <el-tag type="success" v-show="scope.row.ppId!=null">{{scope.row.ppId}}</el-tag>&nbsp; {{scope.row.ppName}}
        </template>
      </el-table-column>
      <el-table-column label="生产数量" align="center" prop="proQty" width="80" />
      <el-table-column label="订单状态" align="center" prop="opState" :formatter="opStateFormat" width="80" />

      <!-- 进度条 根据完成数量计算  -->
      <el-table-column label="进度" align="center">
        <template slot-scope="scope">

          完成数:
          <span>{{scope.row.finQty}}</span>/
          <span>{{scope.row.proQty}}</span>

          <el-progress :text-inside="true" :percentage="finQtyPer(scope.row)" :format="finQtyFormat"
            :color="customColorMethod"></el-progress>
        </template>
      </el-table-column>
      <el-table-column label="不合格数" align="center" prop="badQty" width="80" />

      <!--      <el-table-column label="计划开始日期" align="center" prop="planStartTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planStartTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="计划结束日期" align="center" prop="planEndTime" width="180" v-if="false">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.planEndTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column> -->
      <el-table-column label="开始日期" align="center" prop="startTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.startTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="结束日期" align="center" prop="endTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.endTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="帐号状态" align="center" prop="status" v-if="false" />
      <el-table-column label="备注" align="center" prop="remark" v-if="false" />
      <el-table-column label="下单日期" align="center" prop="createTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime, '{y}-{m}-{d} {h}:{i}:{s}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="制单人" align="center" prop="createBy" width="100">
      </el-table-column>

      <el-table-column label="操作" align="center" class-name="fixed-width" width="220">
        <template slot-scope="scope">

          <!--          <el-button style="padding: 2px;" type="primary" icon="el-icon-s-data" @click="showDetail(scope.row)"
            v-hasPermi="['mes:product_store:edit']">详情</el-button> -->

          <el-button style="padding: 2px;" type="success" icon="el-icon-edit" @click="handleUpdate(scope.row)"
            v-hasPermi="['mes:order_product:edit']">修改</el-button>
          <el-button style="padding: 2px;" type="danger" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['mes:order_product:remove']">删除</el-button>


        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改生产订单对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="订单编号" prop="opId">
          <el-input v-model="form.opId" placeholder="自动生成" :disabled="true" />
        </el-form-item>
        <el-form-item label="产品" prop="ppId">
          <el-col :span="11">
            <el-input v-model="form.ppId" placeholder="产品编号" style="width: 100%;" readonly />
          </el-col>
          <el-col class="line" :span="1" style="text-align: center;">-</el-col>
          <el-col :span="12">
            <el-input v-show="form.opId==null" v-model="form.ppName" placeholder="产品名称" style="width: 100%;" readonly>
              <el-button slot="append" icon="el-icon-search" @click="handleCheckMetail"></el-button>
            </el-input>
            <el-input v-show="form.opId!=null" v-model="form.ppName" placeholder="产品名称" style="width: 100%;" readonly />

          </el-col>
        </el-form-item>

        <el-form-item label="生产数量" prop="proQty">
          <el-input-number v-show="form.opId==null" v-model="form.proQty" controls-position="right" :min="1" :max="10">
          </el-input-number>
          <el-input v-show="form.opId!=null" v-model="form.proQty" style="width: 100px;" readonly />
        </el-form-item>

        <!--     <el-form-item label="订单状态" prop="opState">
          <el-input v-model="form.opState" placeholder="请输入订单状态" />
        </el-form-item> -->

        <!--        <el-form-item label="计划开始日期" prop="planStartTime" v-show="form.opId==null">
          <el-date-picker clearable size="small" v-model="form.planStartTime" type="datetime"
            value-format="yyyy-MM-dd HH:mm:ss" placeholder="选择计划开始日期">
          </el-date-picker>(选填，不填则会立即执行)
        </el-form-item> -->
        <!--        <el-form-item label="计划结束日期" prop="planEndTime">
          <el-date-picker clearable size="small" v-model="form.planEndTime" type="date" value-format="yyyy-MM-dd"
            placeholder="选择计划结束日期">
          </el-date-picker>
        </el-form-item> -->
        <!--        <el-form-item label="开始日期" prop="startTime">
          <el-date-picker clearable size="small" v-model="form.startTime" type="date" value-format="yyyy-MM-dd"
            placeholder="选择开始日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="结束日期" prop="endTime">
          <el-date-picker clearable size="small" v-model="form.endTime" type="date" value-format="yyyy-MM-dd"
            placeholder="选择结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="帐号状态">
          <el-radio-group v-model="form.status">
            <el-radio label="1">请选择字典生成</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="删除标志" prop="delFlag">
          <el-input v-model="form.delFlag" placeholder="请输入删除标志" />
        </el-form-item> -->
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <el-dialog title="选择物料" :visible.sync="m_open" width="550px" append-to-body>
        <el-table :data="metailList">
          <el-table-column label="物料编码" align="center" prop="mId" />
          <el-table-column label="物料名称" align="center" prop="mName" />
          <el-table-column label="物料类型" align="center" prop="mType" :formatter="mTypeFormat" />
          <el-table-column label="计量单位" align="center" prop="mUnit" :formatter="mUnitFormat" />
          <el-table-column label="物料图片">

            <template slot-scope="scope">

              <el-image style="width: 60px; height: 50px" :src="scope.row.mImg"
                :preview-src-list="getImgList(scope.row.mImg)">
                <div slot="error" class="image-slot">

                </div>
              </el-image>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="left">
            <template slot-scope="scope">
              <el-button size="mini" type="success" icon="el-icon-check" @click="checkMetail(scope.row)">选择</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="metailListPage_total>0" :total="metailListPage_total"
          :page.sync="metail_queryParams.pageNum" :limit.sync="metail_queryParams.pageSize"
          @pagination="getlistMaterial" :page-sizes="metailListPage_pageSizes" />
      </el-dialog>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="订单详情" :visible.sync="detail_open" width="600px" append-to-body>

    </el-dialog>

  </div>
</template>

<script>
  import {
    listOrder_product,
    getOrder_product,
    delOrder_product,
    addOrder_product,
    updateOrder_product,
    exportOrder_product
  } from "@/api/mes/order_product";

  import {
    listMaterial
  } from "@/api/mes/material";
  import mqtt from 'mqtt';
  export default {
    name: "Order_product",
    components: {},
    data() {
      return {
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 生产订单表格数据
        order_productList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        // 订单状态字典
        opStateOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          opId: null,
          ppId: null,
          proQty: null,
          opState: null,
          planStartTime: null,
          planEndTime: null,
          startTime: null,
          endTime: null,
          status: null,
        },
        // 表单参数
        form: {
          opId: null,
          proQty: 1,
        },
        // 表单校验
        rules: {
          /*        opId: [{
                     required: true,
                     message: "不能为空",
                     trigger: "blur"
                   }], */
          ppId: [{
            required: true,
            message: "不能为空",
            trigger: "blur"
          }],
        },
        //物料模态框

        m_open: false,
        metailList: [],
        // 物料类型A 成品 B 半成品 C原材料字典
        mTypeOptions: [],
        // 计量单位字典
        mUnitOptions: [],
        metail_queryParams: {
          pageNum: 1,
          pageSize: 5,
          mId: null,
          mName: null,
          mType: "A",
          mUnit: null,
          mImg: null,
          mRace: null,
          mDes: null,
          status: null,
        },
        metailListPage_total: 0,
        metailListPage_pageSizes: [5],
        detail_open: false,
        websock: null,
        mqtt_client: null,
        mqtt_options: {
          clean: true, // true: 清除会话, false: 保留会话
          connectTimeout: 4000, // 超时时间
          // 认证信息
          clientId: 'emqx_web',
          username: 'emqx_web',
          password: 'emqx_web',
        }


      };
    },
    created() {
      //this.initWebSocket();
      this.initMqtt()
      this.getList();
      this.getDicts("op_state").then(response => {
        this.opStateOptions = response.data;
      });

    },
    destroyed() {
      this.mqtt_client.end() //离开路由之后断开websocket连接
    },
    methods: {
      getImgList(img) {
        let images = new Array();
        images.push(img);
        return images;

      },
      /** 查询生产订单列表 */
      getList() {
        this.loading = true;
        listOrder_product(this.queryParams).then(response => {
          this.order_productList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      // 订单状态字典翻译
      opStateFormat(row, column) {
        return this.selectDictLabel(this.opStateOptions, row.opState);
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: null,
          opId: null,
          ppId: null,
          proQty: null,
          opState: null,
          planStartTime: null,
          planEndTime: null,
          startTime: null,
          endTime: null,
          status: "0",
          delFlag: null,
          createBy: null,
          createTime: null,
          updateBy: null,
          updateTime: null,
          remark: null
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "创建生产订单";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const id = row.id || this.ids
        getOrder_product(id).then(response => {
          this.form = response.data;
          this.open = true;
          this.title = "修改生产订单";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != null) {
              updateOrder_product(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addOrder_product(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        });
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除生产订单编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delOrder_product(ids);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        })
      },
      /** 导出按钮操作 */
      handleExport() {
        const queryParams = this.queryParams;
        this.$confirm('是否确认导出所有生产订单数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportOrder_product(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
      },
      // 物料类型A 成品 B 半成品 C原材料字典翻译
      mTypeFormat(row, column) {
        return this.selectDictLabel(this.mTypeOptions, row.mType);
      },
      // 计量单位字典翻译
      mUnitFormat(row, column) {
        //  console.log(this.selectDictLabel(this.mUnitOptions, row.mUnit))
        return this.selectDictLabel(this.mUnitOptions, row.mUnit);
      },
      handleCheckMetail() {

        this.m_open = true;
        this.getlistMaterial();

      },
      getlistMaterial() {
        //获取物料
        listMaterial(this.metail_queryParams).then(response => {
          this.metailList = response.rows;
          this.metailListPage_total = response.total;

        });

        this.getDicts("m_type").then(response => {
          this.mTypeOptions = response.data;
        });
        this.getDicts("m_unit").then(response => {
          this.mUnitOptions = response.data;
        });

      },
      //选择物料
      checkMetail(row) {
        // console.log(row)
        this.form.ppId = row.mId;
        this.form.ppName = row.mName;
        this.m_open = false;
      },
      //详情弹框
      showDetail(row) {
        this.detail_open = true;

        //console.log(row)
      },

      //进度条
      finQtyFormat(percentage) {
        //console.log(percentage)

      },
      finQtyPer(row) {

        return row.finQty / row.proQty * 100
      },
      customColorMethod(percentage) {

        if (percentage == 100) {
          return '#67C23A';
        } else {
          return '#409EFF';
        }

      },
      initMqtt() {
        var that = this;
        that.mqtt_client = mqtt.connect("ws://39.106.111.79:8083/mqtt", this.mqtt_options);
        that.mqtt_client.on('connect', function() {
          that.mqtt_client.subscribe('from/station/function', function(err) {})

        })


        that.mqtt_client.on('message', function(topic, message) {
          var jsonMsg = JSON.parse(message.toString());
          console.log(jsonMsg)
          that.getList();

        })


      },

      //websocket
      // initWebSocket() { //初始化weosocket
      //   const wsuri = "ws://localhost:8080/ws/order_page";
      //   this.websock = new WebSocket(wsuri);
      //   this.websock.onmessage = this.websocketonmessage;
      //   this.websock.onopen = this.websocketonopen;
      //   this.websock.onerror = this.websocketonerror;
      //   this.websock.onclose = this.websocketclose;
      //   console.log("初始化weosocket")
      // },
      // websocketonopen() { //连接建立之后执行send方法发送数据
      //   // let actions = {"test":"12345"};
      //   // t  console.log('断开连接',e);his.websocketsend(JSON.stringify(actions));
      //   console.log('连接成功');
      // },
      // websocketonerror() { //连接建立失败重连
      //   this.initWebSocket();
      // },
      // websocketonmessage(e) { //数据接收
      //   //const redata = JSON.parse(e.data);
      //   console.log(e.data)

      //   if (e.data == "refresh") {
      //     //刷新数据
      //     this.getList();

      //   }

      // },
      // websocketsend(Data) { //数据发送
      //   this.websock.send(Data);
      // },
      // websocketclose(e) { //关闭
      //   console.log('断开连接', e);
      // },


    }
  };
</script>
